import { ref, computed, reactive } from 'vue'
import { defineStore } from 'pinia'
import {
  getToken as getDbToken,
  requestLogin,
  setToken,
  getUserInfo,
  removeToken,
  updateUserAvatar,
} from '@/utils/auth.js'
import useKnowledgeStore from '@/stores/knowledge.js'

const emptyInfo = {
  user_info_id: 0,
  code: '',
  name: '',
  avatar: '',
  pwd_changed: null,
  type: undefined,
  read_password: undefined,
}

const useUserStore = defineStore('user', () => {
  const token = ref('')
  const info = reactive({ ...emptyInfo })

  const setLogin = async (loginInfo) => {
    const t = await requestLogin(loginInfo)
    if (t === false) {
      return "bind"
    }
    if (!t || t === '') {
      return false
    }
    token.value = t
    setToken(t)
    return true
  }

  const getToken = computed(() => {
    if (!token.value) {
      token.value = getDbToken()
    }
    return token.value
  })

  const getInfo = async (refresh = false) => {
    if (!info.code || refresh) {
      const userInfo = await getUserInfo(getToken)
      if (userInfo !== false) {
        Object.keys(userInfo).forEach((key) => {
          info[key] = userInfo[key]
        })
      }
    }
    return info
  }

  const setAvatar = async (avatar) => {
    const result = await updateUserAvatar(avatar)
    if (result) {
      info.avatar = avatar
    }
    return result
  }

  const logout = () => {
    removeToken()
    token.value = ''
    const ks = useKnowledgeStore()
    ks.setKnowledge(0, '')
    Object.keys(emptyInfo).forEach((key) => {
      info[key] = emptyInfo[key]
    })
  }

  const setStrToken = (t) => {
    token.value = t
  }

  return { getToken, setLogin, logout, getInfo, info, setAvatar, setStrToken }
})

export default useUserStore
